package cn.hw.sso.filter;

import cn.hw.sso.util.RpcUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class ClientFilter implements Filter {
    private static String applicationName;
    private static String serverUrl;

    public ClientFilter() {
    }

    @Override
    public void init(FilterConfig filterConfig) {
        applicationName = filterConfig.getInitParameter("applicationName");
        serverUrl = filterConfig.getInitParameter("serverUrl");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        //退出
        if (!StringUtils.isEmpty(req.getRequestURI()) && req.getRequestURI().endsWith("/logOut")) {
            System.out.println("退出了");
            session.invalidate();
            return;
        }
        //由单点登录服务器模仿浏览器登录
        if (!StringUtils.isEmpty(req.getRequestURI()) && req.getRequestURI().endsWith("/login")) {
            if (applicationName.equals(req.getParameter("name"))) {
                String userInfo = req.getParameter("userInfo");
                System.out.println("从服务端获取数据" + userInfo);
                session.setAttribute("loginUser", JSON.parseObject(userInfo));
                return;
            }
        }
        Object isLogin = session.getAttribute("loginUser");
        if (isLogin != null) {
            resp.setStatus(200);
            chain.doFilter(req, resp);
            return;
        } else {
            String token = req.getParameter("token");
            if (token != null && !"".equals(token.trim())) {
                String verifyUrl = serverUrl + "/verify";
                JSONObject param = new JSONObject();
                param.put("token", token);
                param.put("jsessionid", session.getId());
                param.put("name", applicationName);
                JSONObject jsonObject = RpcUtil.httpInvoke(verifyUrl, param, null, HttpMethod.POST, false, JSONObject.class);
                System.out.println(jsonObject);
                if (jsonObject.getBoolean("ok")) {
                    resp.setStatus(200);
                    chain.doFilter(req, resp);
                    return;
                }
            }

            resp.sendRedirect(serverUrl + "/login.html?redirectUrl=" + req.getRequestURL());
        }
    }

    @Override
    public void destroy() {
    }
}
